﻿namespace SpaceshipDuel
{
    using System;
    using Microsoft.Xna.Framework.Audio;
    using NVorbis;

    /// <summary>
    /// Based on code from: 
    /// http://xboxforums.create.msdn.com/forums/p/111666/667774.aspx
    /// which based on Ogg Wrapper using NVorbis by Nick Gravelyn 
    /// https://gist.github.com/nickgravelyn/5580531
    /// </summary>
    class OggSong : IDisposable
    {
        private VorbisReader reader;
        private SoundEffect effect;

        private byte[] buffer;
        private float[] nvBuffer;

        public bool IsLooped { get; set; }

        public OggSong(string oggFile)
        {
            reader = new VorbisReader(oggFile);

            buffer = new byte[SoundEffect.GetSampleSizeInBytes(reader.TotalTime, reader.SampleRate, (AudioChannels)reader.Channels)];
            nvBuffer = new float[buffer.Length / 2];
            int samplesRead;
            while ((samplesRead = reader.ReadSamples(nvBuffer, 0, nvBuffer.Length)) > 0)
            {
                for (int i = 0; i < samplesRead; i++) 
                {
                    short sValue = (short)Math.Max(Math.Min(short.MaxValue * nvBuffer[i], short.MaxValue), short.MinValue);
                    buffer[i * 2] = (byte)(sValue & 0xff);
                    buffer[i * 2 + 1] = (byte)((sValue >> 8) & 0xff);
                }
            }

            effect = new SoundEffect(buffer, reader.SampleRate, (AudioChannels)reader.Channels);
        }

        ~OggSong()
        {
            Dispose(false);
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected void Dispose(bool isDisposing)
        {
            effect.Dispose();
        }

        public SoundEffect Effect
        {
            get { return effect; }
        }
    } 
}
